import java.util.ArrayDeque;
import java.util.Deque;
import java.util.Queue;

public class Main {
    public static void main(String[] args) {
        System.out.println("Hello world!");
    }
}

class TreeNode {
    int val;
    TreeNode left;
    TreeNode right;
    TreeNode() {}
    TreeNode(int val) { this.val = val; }
    TreeNode(int val, TreeNode left, TreeNode right) {
        this.val = val;
        this.left = left;
        this.right = right;
    }
}
class Solution {
    public int sumOfLeftLeaves(TreeNode root) {
        if (root == null) {
            return 0;
        }
        if (root.left != null && isLeaf(root.left)) {
            return root.left.val + sumOfLeftLeaves(root.right);
        }
        return sumOfLeftLeaves(root.left) + sumOfLeftLeaves(root.right);
    }

    boolean isLeaf(TreeNode node) {
        return node.left == null && node.right == null;
    }
}

//迭代
class Solution1 {
    public int sumOfLeftLeaves(TreeNode root) {
        if (root == null) {
            return 0;
        }
        Deque<TreeNode> stack = new ArrayDeque<>();
        stack.push(root);
        int ans = 0;
        while (!stack.isEmpty()) {
            TreeNode cur = stack.pop();
            if (cur.right != null) {
                stack.push(cur.right);
            }
            if (cur.left != null) {
                if (isLeaf(cur.left)) {
                    ans += cur.left.val;
                } else {
                    stack.push(cur.left);
                }
            }
        }
        return ans;
    }

    boolean isLeaf(TreeNode node) {
        return node.left == null && node.right == null;
    }
}

//层序遍历
class Solution2 {
    public int sumOfLeftLeaves(TreeNode root) {
        if (root == null) {
            return 0;
        }
        Queue<TreeNode> queue = new ArrayDeque<>();
        queue.offer(root);
        int ans = 0;
        while (!queue.isEmpty()) {
            TreeNode cur = queue.poll();
            if (cur.left != null) {
                if (isLeaf(cur.left)) {
                    ans += cur.left.val;
                } else {
                    queue.offer(cur.left);
                }
            }
            if (cur.right != null) {
                queue.offer(cur.right);
            }
        }
        return ans;
    }

    boolean isLeaf(TreeNode node) {
        return node.left == null && node.right == null;
    }
}